package com.example.medicalzb.service;

import com.example.medicalzb.mapper.FileUploadMapper;
import com.example.medicalzb.util.Msg;
import org.apache.tomcat.util.http.fileupload.FileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

@Service
@Transactional
public class FileUploadService {
    @Autowired
    private FileUploadMapper fileUploadMapper;
    public Msg upload(MultipartFile file) {
        OutputStream os = null;
        InputStream is = null;
        String fileName = null;
        int len;
        try {
            is = file.getInputStream();
            fileName = UUID.randomUUID() + file.getOriginalFilename();
            String path = "D:\\mzyJava\\medical-zb\\src\\main\\resources\\images";
            byte[] bytes = new byte[1024];
            File tmpFile = new File(path);
            if (!tmpFile.exists()){
                tmpFile.mkdirs();
            }
            os = new FileOutputStream(tmpFile.getPath() + File.separator + fileName);
            while ((len = is.read(bytes)) != -1){
                os.write(bytes,0,len);
            }
            os.flush();
            os.close();
            is.close();

        } catch (IOException e) {
            return Msg.fail().mess("上传失败");
        }
        String url = "http://localhost:8080/image/" + fileName;
        return Msg.success().mess("上传成功").data("url",url);
    }
}
